package com.qiankan.qmsj.adapter;


import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.lang.reflect.Constructor;
import java.util.List;

public abstract class CommonAdapter<T> extends RecyclerView.Adapter {
    protected List<T> mDatas;
    protected Context mContext;
    protected LayoutInflater mInflater;
    protected final int mItemLayoutId;
    protected Class<? extends RecyclerView.ViewHolder> viewHolderClass;

    public CommonAdapter(Context context, Class viewHolderClass, List<T> mDatas, int itemLayoutId) {
        this.mContext = context;
        this.mDatas = mDatas;
        this.mItemLayoutId = itemLayoutId;
        this.viewHolderClass = viewHolderClass;
        this.mInflater = LayoutInflater.from(mContext);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(mItemLayoutId, null);
        try {
            Constructor<? extends RecyclerView.ViewHolder> constructor = viewHolderClass.getConstructor(View.class);
            return constructor.newInstance(view);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        convert(holder, mDatas.get(position), position);
    }

    @Override
    public int getItemCount() {
        return mDatas.size();
    }

    public abstract void convert(RecyclerView.ViewHolder holder, T item, int position);
}
